package com.sat.client.vm

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.sat.client.api.NetworkAPI
import com.sat.client.bean.DeviceInfo
import com.sat.client.bean.FileItem
import com.sat.common.base.BaseViewModel
import com.sat.common.base.SingleLiveEvent
import com.sat.common.network.RetrofitFactory
import com.sat.common.network.RetrofitParams
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress

class MainFragmentVM : BaseViewModel() {


    //发现的设备列表
    private val _deviceInfos: SingleLiveEvent<List<DeviceInfo>> =
        SingleLiveEvent<List<DeviceInfo>>()
    val deviceInfos: LiveData<List<DeviceInfo>> = _deviceInfos

    private val _fileItem: SingleLiveEvent<FileItem> =
        SingleLiveEvent<FileItem>()
    val fileItem: LiveData<FileItem> = _fileItem
    private suspend fun sendBroadcastMessage(message: String, port: Int) {
        withContext(Dispatchers.IO) {
            DatagramSocket().use { socket ->
                socket.broadcast = true
                val address = InetAddress.getByName("255.255.255.255") // 广播地址
                val packet = DatagramPacket(message.toByteArray(), message.length, address, port)
                socket.send(packet)
            }
        }
    }

    fun scanDevices() {
        viewModelScope.launch {
            defUI.showDialog.call()
            sendBroadcastMessage("SAT_DEVICE_DISCOVER", 9898)
            val deviceInfoStatus = receiveResponses(9999)
            deviceInfoStatus.add(DeviceInfo("234234","172.16.10.23",null,"D320"))
            deviceInfoStatus.add(DeviceInfo("234234","172.16.10.23",null,"D320"))
            deviceInfoStatus.add(DeviceInfo("234234","172.16.10.23",null,"D320"))
            deviceInfoStatus.add(DeviceInfo("234234","172.16.10.23",null,"D320"))
            _deviceInfos.value=deviceInfoStatus
            defUI.dismissDialog.call()
        }
    }

    private fun initRetrofit(ip: String,port: Int) {
        RetrofitFactory.init(
            RetrofitParams.newBuilder()
                .baseUrl("http://$ip:$port")
                .build()
        )
        NetworkAPI.initApiServer()
    }

    fun getFiles(ip: String,port: Int) {
        initRetrofit(ip,port)
        launchCommon(
            { NetworkAPI.api.getFiles() },
            {
                _fileItem.value=it
            },
        )
    }

    private suspend fun receiveResponses(port: Int): MutableList<DeviceInfo> {
        val responses = mutableListOf<DeviceInfo>()
        withContext(Dispatchers.IO) {
            DatagramSocket(port).use { socket ->
                socket.soTimeout = 2 * 1000 // 设置超时时间
                val buffer = ByteArray(1024)
                while (true) {
                    val packet = DatagramPacket(buffer, buffer.size)
                    val gson = Gson()
                    try {
                        socket.receive(packet)
                        val response = String(packet.data, 0, packet.length)
                        Log.e("test", response)
                        responses.add(gson.fromJson(response, DeviceInfo::class.java))
                    } catch (e: Exception) {
                        // 超时或其他异常处理
                        e.printStackTrace()
                        break
                    }
                }
            }
        }
        return responses
    }
}